import {requestConfig} from '@/requestConfig';
import {getKey, regenerationKey, userLogout} from '@/services/shApi-backend/userController';
import {useModel} from '@@/exports';
import {PageContainer} from '@ant-design/pro-components';
import {Avatar, Button, Card, Descriptions, message, Space} from 'antd';
import React, {useState} from 'react';

/**
 * 接口详情页面
 * @constructor
 */
const Index: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<API.UserDevKeyVO>();
  const [updateModalShow, setUpdateModalShow] = useState<boolean>(false);
  const {initialState, setInitialState} = useModel('@@initialState');
  const {loginUser} = initialState;
  const [imageUrl, setImageUrl] = useState<string | null>(loginUser?.userAvatar ?? null);
  console.log('shuju：', loginUser);
  const loadData = async () => {
    setLoading(true);
    try {
      const res = await getKey();
      // console.log(res);
      console.log(res.data);
      setData(res.data);
    } catch (e: any) {
      message.error('获取数据失败，' + e.message);
    }
    setLoading(false);
    return;
  };
  const showDevKey = () => {
    loadData();
  };

  const showRegenerationKey = async () => {
    try {
      const res = await regenerationKey();
      setData(res.data);
    } catch (e: any) {
      message.error('获取数据失败，' + e.message);
    }
  };

  const getSdk = () => {
    window.location.href = requestConfig.baseURL + '/apibackend/interfaceInfo/sdk';
  };


  const loginOut = async () => {
    await userLogout();
    const {search, pathname} = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    /** 此方法会跳转到 redirect 参数所在的位置 */
    const redirect = urlParams.get('redirect');
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/user/login' && !redirect) {
      window.location.href = '/user/login';
    }
  };
  const  url = 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png';

  return (
    <PageContainer title={'个人中心'}>
      <Space direction="vertical" size="middle" style={{display: 'flex'}}>
        <Card
          title="您的信息"
          extra={
            <>
              <Space>
                <Button onClick={loginOut}>退出</Button>
              </Space>
            </>
          }
        >
          {loginUser ? (
            <Descriptions /*title={'您的信息'}*/ column={2}>

              <Descriptions.Item label="头像">
                <Avatar
                  size={64} // 指定头像尺寸
                  src={imageUrl ?? url}
                  onError={() => {
                    console.log('头像加载失败');
                    return false; // 返回 false 会触发 fallback 到 children
                  }}
                >
                  头像
                </Avatar>
              </Descriptions.Item>
              <Descriptions.Item title={'dss'} label="账号">
                {loginUser.userAccount}
              </Descriptions.Item>
              <Descriptions.Item label="角色">{loginUser.userRole}</Descriptions.Item>
              <Descriptions.Item label="创建时间">{loginUser.createTime}</Descriptions.Item>
            </Descriptions>
          ) : (
            <>登录状态异常</>
          )}
        </Card>

        <Card
          title="开发者密钥（调用接口的凭证）"
          extra={
            <>
              <Space>
                <Button onClick={getSdk}>下载SDK</Button>
                <Button onClick={showDevKey}>显示密钥</Button>
                <Button onClick={showRegenerationKey}>重新生成</Button>
              </Space>
            </>
          }
        >
          <Descriptions column={1} bordered size="small" layout="vertical">
            <Descriptions.Item label="accessKey" copyable={{tooltips: false}}>
              {data?.accessKey ?? '******************'}
            </Descriptions.Item>
            <Descriptions.Item label="secretKey" copyable={{tooltips: false}}>
              {data?.secretKey ?? '******************'}
            </Descriptions.Item>
          </Descriptions>
        </Card>
      </Space>
    </PageContainer>
  );
};

export default Index;
